
from sanic import Blueprint

from controllers.strategy import StrategyController
from decorators import response_json
from utils.parser import parse_args

bp = Blueprint("strategy", url_prefix="/strategy")


@bp.route("", methods=["GET", "POST"])
@response_json
async def strategy(request):
    """指标列表"""
    if request.method == "GET":
        return StrategyController.all_strategys()
    elif request.method == "POST":
        args_rules = [
            dict(arg="name", required=True, type="str"),
            dict(arg="orient", required=True, type="int"),
            # dict(arg="indicator_abbr", required=True, type="str"),
            # dict(arg="params", required=True, type="str"),
            dict(arg="condition", required=True, type="str"),
            dict(arg="available", required=False, type="str"),
        ]
        args = parse_args(request, "json", args_rules)
        StrategyController.create(**args)


@bp.route("/<id:int>", methods=["GET", "DELETE", "PUT"])
@response_json
async def strategy_id(request, id):
    """ 指标的单个操作
    """
    strategy_ctl = StrategyController(id)
    if request.method == "GET":
        return strategy_ctl.strategy
    elif request.method == "DELETE":
        strategy_ctl.delete()
        return {}
    elif request.method == "PUT":
        args_rules = [
            dict(arg="name", required=False, type="str"),
            dict(arg="orient", required=False, type="str"),
            # dict(arg="indicator_abbr", required=False, type="str"),
            # dict(arg="params", required=False, type="str"),
            dict(arg="condition", required=False, type="str"),
            dict(arg="available", required=False, type="str"),
        ]
        args = parse_args(request, "json", args_rules)
        strategy_ctl.update(**args)
        return {}

@bp.route("/statistic", methods=["GET"])
@response_json
async def strategy_statistic(request):
    """ 触发统计 """
    args_rules = [
        dict(arg="cal_date", dest="cal_date_int", required=False, type="int")
    ]
    args = parse_args(request, "args", args_rules)
    return StrategyController.strategy_statistic(args.get("cal_date_int"))


@bp.route("/<id:int>/trigger_stock", methods=["GET"])
@response_json
async def trigger_stock(request, id):
    """ 策略所触发的股票
    """
    args_rules = [
        dict(arg="cal_date", dest="cal_date_int", required=False, type="int")
    ]
    args = parse_args(request, "args", args_rules)
    return StrategyController(id=id).get_strategy_trigger_stock(args.get("cal_date_int"))


@bp.route("/trigger/statistic", methods=["GET"])
@response_json
async def trigger_statistic(request):
    args_rules = [
        dict(arg="cal_date", dest="cal_date_int", required=False, type="int")
    ]
    args = parse_args(request, "args", args_rules)
    return StrategyController.trigger_statistic(args.get("cal_date_int"))

